#!/usr/bin/env python3.7.9
'''
Copyright © 2021 DUE TUL
@ date  : Friday january 15, 2020
@ desc  : This modules is used to train date
@ author:  
'''
import tensorflow as tf
import reader
import numpy as np
import math
import librosa
import librosa.display
import matplotlib.pyplot  as plt
import random
import requests


def save(str, name):
    file = open("dataset/demo_test/" + name, "w")
    file.write(str)
    file.close()


def ff(str):
    return str.replace(',', '')


def simulate():
    x = np.ones(768).tolist()
    x2 = np.full(768, 100).tolist()
    x3 = np.full(768, 1000).tolist()
    x4 = np.full(768, 10000).tolist()
    y = "%s, %s, %s" % (ff(str(x)), ff(str(x)), ff(str(x)))
    y2 = "%s, %s, %s" % (ff(str(x2)), ff(str(x2)), ff(str(x2)))
    y3 = "%s, %s, %s" % (ff(str(x3)), ff(str(x3)), ff(str(x3)))
    y4 = "%s, %s, %s" % (ff(str(x4)), ff(str(x4)), ff(str(x4)))
    str = str2 = str3 = str4 = ''
    for i in range(100):
        str += '%s, %s\n' % (i, y)
        str2 += '%s, %s\n' % (i, y2)
        str3 += '%s, %s\n' % (i, y3)
        str4 += '%s, %s\n' % (i, y4)
    save(str, 'move.txt')
    save(str2, 'close.txt')
    save(str3, 'open.txt')
    save(str4, 'rotation.txt')
def create_data_tfrecord(data_list_path, save_path):
    with open(data_list_path, 'r') as f:
        data = f.readlines()
    with tf.io.TFRecordWriter(save_path) as writer:
        for d in data:
            try:
                path, label = d.replace('\n', '').split('\t')
                wav, sr = librosa.load(path, sr=16000)
                intervals = librosa.effects.split(wav, top_db=20)
                wav_output = []
                # wave data length 16000 * time
                wav_len = int(16000 * 2.04)
                for sliced in intervals:
                    wav_output.extend(wav[sliced[0]:sliced[1]])
                for i in range(5):
                    # print(i)
                    # Cut the excess audio data
                    if len(wav_output) > wav_len:
                        l = len(wav_output) - wav_len
                        r = random.randint(0, l)
                        wav_output = wav_output[r:wav_len + r]
                    else:
                        wav_output.extend(np.zeros(shape=[wav_len - len(wav_output)], dtype=np.float32))
                    wav_output = np.array(wav_output)*1.2
                    # Convert to Mel spectrum
                    ps = librosa.feature.melspectrogram(y=wav_output, sr=sr, hop_length=256).reshape(-1).tolist()
                    # Mel spectrum size ，librosa.feature.melspectrogram(y=wav_output, sr=sr, hop_length=256).shape
                    if len(ps) != 128 * 128: continue
                    tf_example = data_example(ps, int(label))
                    writer.write(tf_example.SerializeToString())
                    if len(wav_output) <= wav_len:
                        break
            except Exception as e:
                print(e)

if __name__ == '__main__':
    # simulate()
    y, sr = librosa.load('dataset/test/1.wav', sr=16000)
    plt.subplot(221)
    librosa.display.waveplot(y, sr)
    melspec = librosa.feature.melspectrogram(y, sr, n_fft=1024, hop_length=512, n_mels=128)
    logmelspec = librosa.power_to_db(melspec)
    plt.subplot(222)
    librosa.display.specshow(logmelspec, sr=sr, x_axis='time')
    intervals = librosa.effects.split(y, top_db=20)
    ps = librosa.feature.melspectrogram(y=y, sr=sr, hop_length=256).astype(np.float32)
    print(ps.shape)
    ps2 = ps[np.newaxis, ..., np.newaxis]
    print("ps2:",ps2.shape)
    plt.show()
